{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 描述\n",
    "Python for循环可以遍历任何序列的项目，如一个列表或者一个字符串。\n",
    "\n",
    "# 语法\n",
    "\n",
    "for循环的语法格式如下：\n",
    "```\n",
    "for iterating_var in sequence:\n",
    "   statements(s)\n",
    "```\n",
    "# 流程图\n",
    "\n",
    "![for-循环-流程图](https://pptwinpics.oss-cn-beijing.aliyuncs.com/for-%E5%BE%AA%E7%8E%AF-%E6%B5%81%E7%A8%8B%E5%9B%BE_20191126162825.jpg)\n",
    "\n",
    "# 实例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当前字母 : P\n",
      "当前字母 : y\n",
      "当前字母 : t\n",
      "当前字母 : h\n",
      "当前字母 : o\n",
      "当前字母 : n\n",
      "当前水果 : banana\n",
      "当前水果 : apple\n",
      "当前水果 : mango\n",
      "Good bye!\n"
     ]
    }
   ],
   "source": [
    "for letter in 'Python':     # 第一个实例\n",
    "   print('当前字母 :', letter)\n",
    " \n",
    "fruits = ['banana', 'apple',  'mango']\n",
    "for fruit in fruits:        # 第二个实例\n",
    "   print('当前水果 :', fruit)\n",
    " \n",
    "print(\"Good bye!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 通过序列索引迭代\n",
    "另外一种执行循环的遍历方式是通过索引，如下实例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当前水果 : banana\n",
      "当前水果 : apple\n",
      "当前水果 : mango\n",
      "Good bye!\n"
     ]
    }
   ],
   "source": [
    "fruits = ['banana', 'apple',  'mango']\n",
    "for index in range(len(fruits)):\n",
    "   print('当前水果 :', fruits[index])\n",
    " \n",
    "print(\"Good bye!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 解读\n",
    "以上实例我们使用了内置函数 len() 和 range(),函数 len() 返回列表的长度，即元素的个数。 range返回一个序列的数。\n",
    "\n",
    "---\n",
    "\n",
    "# 循环使用 else 语句\n",
    "在 python 中，for … else 表示这样的意思，for 中的语句和普通的没有区别，else 中的语句会在循环正常执行完（即 for 不是通过 break 跳出而中断的）的情况下执行，while … else 也是一样。\n",
    "\n",
    "# 实例\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10 等于 2 * 5\n",
      "11 是一个质数\n",
      "12 等于 2 * 6\n",
      "13 是一个质数\n",
      "14 等于 2 * 7\n",
      "15 等于 3 * 5\n",
      "16 等于 2 * 8\n",
      "17 是一个质数\n",
      "18 等于 2 * 9\n",
      "19 是一个质数\n"
     ]
    }
   ],
   "source": [
    "for num in range(10,20):  # 迭代 10 到 20 之间的数字\n",
    "   for i in range(2,num): # 根据因子迭代\n",
    "      if num%i == 0:      # 确定第一个因子\n",
    "         j=num/i          # 计算第二个因子\n",
    "         print('%d 等于 %d * %d' % (num,i,j))\n",
    "         break            # 跳出当前循环\n",
    "   else:                  # 循环的 else 部分\n",
    "      print(num, '是一个质数')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 其他实例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 12\n",
      "1 34\n",
      "2 34\n",
      "3 23\n",
      "4 45\n",
      "5 76\n",
      "6 89\n"
     ]
    }
   ],
   "source": [
    "# 使用内置 enumerate 函数进行遍历\n",
    "sequence = [12, 34, 34, 23, 45, 76, 89]\n",
    "for i, j in enumerate(sequence):\n",
    "    print(i,j)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n"
     ]
    }
   ],
   "source": [
    "# 使用list.append()模块对质数进行输出\n",
    "# 输出 2 到 100 简的质数\n",
    "prime = []\n",
    "for num in range(2,100):  # 迭代 2 到 100 之间的数字\n",
    "   for i in range(2,num): # 根据因子迭代\n",
    "      if num%i == 0:      # 确定第一个因子\n",
    "         break            # 跳出当前循环\n",
    "   else:                  # 循环的 else 部分\n",
    "      prime.append(num)\n",
    "print(prime)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入行数：10\n",
      "                                     *                                      \n",
      "\n",
      "                                 *       *                                  \n",
      "\n",
      "                             *               *                              \n",
      "\n",
      "                         *                       *                          \n",
      "\n",
      "                     *                               *                      \n",
      "\n",
      "                 *                                       *                  \n",
      "\n",
      "             *                                               *              \n",
      "\n",
      "         *                                                       *          \n",
      "\n",
      "     *                                                               *      \n",
      "\n",
      " *       *       *       *       *       *       *       *       *       *  \n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 打印空心等边三角形\n",
    "rows = int(input('输入行数：'))\n",
    "for i in range(0, rows):\n",
    "    for k in range(0, 2 * rows - 1):\n",
    "        if (i != rows - 1) and (k == rows - i - 1 or k == rows + i - 1):\n",
    "            print(\" * \", end=\" \"),\n",
    "        elif i == rows - 1:\n",
    "            if k % 2 == 0:\n",
    "                print(\" * \", end=\" \"),\n",
    "            else:\n",
    "                print(\"   \", end=\" \"),\n",
    "        else:\n",
    "            print(\"   \", end=\" \"),\n",
    "    print('\\n')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "1 \n",
      "\n",
      "1 2 \n",
      "\n",
      "1 2 3 \n",
      "\n",
      "1 2 3 4 \n",
      "\n",
      "1 2 3 4 5 \n",
      "\n",
      "1 2 3 4 5 6 \n",
      "\n",
      "1 2 3 4 5 6 7 \n",
      "\n",
      "1 2 3 4 5 6 7 8 \n",
      "\n",
      "1 2 3 4 5 6 7 8 9 \n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 打印1-9三角形阵列\n",
    "for i in range(1,11):\n",
    "    for k in range(1,i):\n",
    "        print(k, end=\" \")\n",
    "    print(\"\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "q\n",
      "z\n",
      "s\n",
      "e\n",
      "c\n",
      "f\n",
      "index=0 ,char=q\n",
      "index=1 ,char=a\n",
      "index=2 ,char=z\n",
      "index=3 ,char=x\n",
      "index=4 ,char=s\n",
      "index=5 ,char=w\n",
      "index=6 ,char=e\n",
      "index=7 ,char=d\n",
      "index=8 ,char=c\n",
      "index=9 ,char=v\n",
      "index=10 ,char=f\n",
      "index=11 ,char=r\n"
     ]
    }
   ],
   "source": [
    "'''在python中，for循环后的in跟随一个序列的话，循环每次使用的序列元素，而不是序列\n",
    "的下标'''\n",
    "s = 'qazxswedcvfr'\n",
    "for i in range(0,len(s),2):\n",
    "    print(s[i])\n",
    "'''enumerate() :\n",
    "    在每次循环中，可以同时得到下标和元素\n",
    "    际上，enumerate(),在每次循环中返回的是包含每个元素的定值表，两个元素分别赋值\n",
    " index，char'''\n",
    "for (index,char) in enumerate(s):\n",
    "    print(\"index=%s ,char=%s\" % (index,char))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 6, 8, 9]\n"
     ]
    }
   ],
   "source": [
    "# 冒泡排序定义列表 list\n",
    "\n",
    "arays = [1,8,2,6,3,9,4]\n",
    "for i in range(len(arays)):\n",
    "    for j in range(i+1):\n",
    "        if arays[i] < arays[j]:\n",
    "            # 实现连个变量的互换\n",
    "            arays[i],arays[j] = arays[j],arays[i]\n",
    "print(arays)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入对角线长度： 10\n",
      "          *            \n",
      "        *   *          \n",
      "      *       *        \n",
      "    *           *      \n",
      "  *               *    \n",
      "*                   *  \n",
      "  *               *    \n",
      "    *           *      \n",
      "      *       *        \n",
      "        *   *          \n",
      "          *            \n"
     ]
    }
   ],
   "source": [
    "# 如果让你画圆或者其他图形呢？其实运用数学公式，就可以了。比如菱形 |x - w/2| + |y - w/2| = w/2 轻松搞定。\n",
    "\n",
    "width = int(input('输入对角线长度： '))\n",
    "for row in range(width + 1):\n",
    "    for col in range(width + 1):\n",
    "        if ((abs(row - width/2) + abs(col - width/2)) == width/2):\n",
    "            print(\"*\", end=\" \"),\n",
    "        else:\n",
    "            print(\" \", end=\" \"),\n",
    "    print(\" \")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "for循环只能执行range内两数字相减次数\n",
      "i=: 1\n",
      "i=: 2\n",
      "i=: 3\n",
      "i=: 4\n",
      "i=: 5\n",
      "i=: 6\n",
      "i=: 7\n",
      "i=: 8\n",
      "i=: 9\n",
      "使用xrange还是一样的效果\n",
      "i=: 1\n",
      "i=: 2\n",
      "i=: 3\n",
      "i=: 4\n",
      "i=: 5\n",
      "i=: 6\n",
      "i=: 7\n",
      "i=: 8\n",
      "i=: 9\n",
      "for i in range(1,1)这样是不会进入循环的\n",
      "而其他语言的 for i=1 to 1 是可以进入一次循环的\n",
      "所以，要执行定次数循环必须将range(1,1)的第二个数字加1\n",
      "for实现step效果递增\n",
      "0\n",
      "2\n",
      "4\n",
      "6\n",
      "8\n",
      "for实现step效果递减\n",
      "10\n",
      "8\n",
      "6\n",
      "4\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "print(\"for循环只能执行range内两数字相减次数\")\n",
    "for i in range(1,10):     # 只能执行9次,判断循环终止条件是 >= 第二个数字 10 就不再执行 和 其他语言的 i=1 to 10 不同\n",
    "    print('i=:', i)\n",
    "\n",
    "print(\"使用xrange还是一样的效果\")\n",
    "for i in range(1,10,1):     #还是只能执行9次,和其他语言的 i=1 to 10 可执行10次是不同的\n",
    "    print('i=:', i)   \n",
    "    \n",
    "print('for i in range(1,1)这样是不会进入循环的')\n",
    "print(\"而其他语言的 for i=1 to 1 是可以进入一次循环的\")\n",
    "for i in range(1,1):     # 也就是说这样是不会进入循环的。\n",
    "    print('没执行这里：i=:', i)\n",
    "print(\"所以，要执行定次数循环必须将range(1,1)的第二个数字加1\")\n",
    "\n",
    "print(\"for实现step效果递增\")\n",
    "for i in range(0,10,2):\n",
    "    print(i)\n",
    "\n",
    "print(\"for实现step效果递减\")\n",
    "for i in range(10,0,-2):\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入列数： 10\n",
      "用for函数书写的正等腰直角三角形\n",
      " *  \n",
      "\n",
      " *   *  \n",
      "\n",
      " *   *   *  \n",
      "\n",
      " *   *   *   *  \n",
      "\n",
      " *   *   *   *   *  \n",
      "\n",
      " *   *   *   *   *   *  \n",
      "\n",
      " *   *   *   *   *   *   *  \n",
      "\n",
      " *   *   *   *   *   *   *   *  \n",
      "\n",
      " *   *   *   *   *   *   *   *   *  \n",
      "\n",
      " *   *   *   *   *   *   *   *   *   *  \n",
      "\n",
      "用for函数书写的倒等腰直角三角形\n",
      " *   *   *   *   *   *   *   *   *   *  \n",
      "\n",
      " *   *   *   *   *   *   *   *   *  \n",
      "\n",
      " *   *   *   *   *   *   *   *  \n",
      "\n",
      " *   *   *   *   *   *   *  \n",
      "\n",
      " *   *   *   *   *   *  \n",
      "\n",
      " *   *   *   *   *  \n",
      "\n",
      " *   *   *   *  \n",
      "\n",
      " *   *   *  \n",
      "\n",
      " *   *  \n",
      "\n",
      " *  \n",
      "\n",
      "用while函数书写的正等腰直角三角形\n",
      "*   \n",
      "\n",
      "*   *   \n",
      "\n",
      "*   *   *   \n",
      "\n",
      "*   *   *   *   \n",
      "\n",
      "*   *   *   *   *   \n",
      "\n",
      "*   *   *   *   *   *   \n",
      "\n",
      "*   *   *   *   *   *   *   \n",
      "\n",
      "*   *   *   *   *   *   *   *   \n",
      "\n",
      "*   *   *   *   *   *   *   *   *   \n",
      "\n",
      "*   *   *   *   *   *   *   *   *   *   \n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 输出各种形状三角形\n",
    "rows = int(input('输入列数： '))\n",
    "print(\"用for函数书写的正等腰直角三角形\")\n",
    "for i in range(0, rows):\n",
    "    for k in range(0, i+1):\n",
    "        print(\" * \", end=\" \"),\n",
    "    print(\"\\n\")\n",
    "print(\"用for函数书写的倒等腰直角三角形\")\n",
    "for i in range(0, rows):\n",
    "    for k in range(0, rows-i):\n",
    "        print(\" * \", end=\" \"),\n",
    "    print(\"\\n\")\n",
    "print(\"用while函数书写的正等腰直角三角形\")\n",
    "i=1\n",
    "while i:\n",
    "    j=1\n",
    "    while j:\n",
    "        print(\"*\",\" \", end=\" \")\n",
    "        if i==j:\n",
    "            break\n",
    "        j+=1\n",
    "        if j>rows:\n",
    "           break\n",
    "    print(\"\\n\")\n",
    "    i+=1\n",
    "    if i>rows:\n",
    "        break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
